package com.youdianda.controller;


import com.youdianda.result.Result;
import com.youdianda.utils.AliOssUtil;
import com.youdianda.vo.UploadVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.UUID;

@RestController("/admin")
@RequestMapping("/common")
@Api(tags = "通用接口")
public class CommonFileController {

    @Autowired
    private AliOssUtil aliOssUtil;


    /**
     * alioss文件上传
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){


        //2.获取文件名
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();

        //切割最后一个点的后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        //文件大小
        long size = file.getSize();

        //文件名称
        String name = UUID.randomUUID().toString().replace("-","")+substring;

        //1.调用工具类

        try {
            //保存地址
            String savePath = aliOssUtil.upload(file.getBytes(), name);

            return Result.success(UploadVO.builder()
                    .savePath(savePath)
                    .name(name)
                    .mime(substring)
                    .size((int) size)
                    .build());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
